package com.collect.senegal.zhiBase;

import com.collect.senegal.zhiUtils.ToastUtil;

import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class BasePresenter<T extends BaseContract.View> implements BaseContract.Presenter<T> {
    protected T mView;
    private WeakReference<T> mViewReference ;

    @Override
    public void attachView(T view) {
        this.mView = view;
        this.mViewReference = new WeakReference<T>(view) ;

        // 用代理对象 动态代理
        mView = (T) Proxy.newProxyInstance(view.getClass().getClassLoader(), view.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // 动态代理每次都会执行这个方法，调用的是被代理的对象（就是mView）
                if (mViewReference == null || mViewReference.get() == null) {
                    return null ;
                }else{
                    return method.invoke(mViewReference.get(), args);
                }
            }
        });
    }

    @Override
    public void detachView() {
        if (mView != null) {
            mView = null;
            mViewReference.clear();
            mViewReference = null ;
        }
    }

    public T getView() {
        return mView;
    }

    public void showMessage(String message){
        ToastUtil.s(message);
    }

    public void showMessageL(String message){
        ToastUtil.l(message);
    }
}